from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models.position import Position
from schemas.position import PositionCreate, PositionRead
from routes.auth import get_current_active_user
from models.user import User

router = APIRouter(
    prefix="/positions",
    tags=["positions"],
    dependencies=[Depends(get_current_active_user)]
)

@router.post("/", response_model=PositionRead)
def create_position(position: PositionCreate, db: Session = Depends(get_db)):
    db_position = Position(**position.dict())
    db.add(db_position)
    db.commit()
    db.refresh(db_position)
    return db_position

@router.get("/{position_id}", response_model=PositionRead)
def read_position(position_id: int, db: Session = Depends(get_db)):
    db_position = db.query(Position).filter(Position.id == position_id).first()
    if not db_position:
        raise HTTPException(status_code=404, detail="Position not found")
    return db_position

@router.get("/", response_model=list[PositionRead])
def read_positions(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    positions = db.query(Position).offset(skip).limit(limit).all()
    return positions

@router.put("/{position_id}", response_model=PositionRead)
def update_position(position_id: int, position: PositionCreate, db: Session = Depends(get_db)):
    db_position = db.query(Position).filter(Position.id == position_id).first()
    if not db_position:
        raise HTTPException(status_code=404, detail="Position not found")
    for var, value in position.dict().items():
        setattr(db_position, var, value) if value is not None else None
    db.commit()
    db.refresh(db_position)
    return db_position

@router.delete("/{position_id}")
def delete_position(position_id: int, db: Session = Depends(get_db)):
    position = db.query(Position).filter(Position.id == position_id).first()
    if not position:
        raise HTTPException(status_code=404, detail="Position not found")
    db.delete(position)
    db.commit()
    return {"message": "Position deleted successfully"}